package cn.edu.seu.ssny.config.filter;

import cn.edu.seu.ssny.entity.User;
import cn.edu.seu.ssny.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器：属于Servlet容器的范畴,不能再里面使用Spring容器内的东西，比如下面的这个自动注入
 */
//@WebFilter(urlPatterns = "/*", filterName = "authrizationFilter")
public class AuthorizationFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(AuthorizationFilter.class);

//    @Autowired
//    IDeviceService deviceService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("进入拦截器AuthorizationFilter");
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();
        User currUser = (User) session.getAttribute("currUser");
        String path = ((HttpServletRequest) servletRequest).getServletPath();
        if (currUser != null || path.contains("login") || path.contains("assets")) {
            // 用户已经登录，直接转发请求
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //使用转发不会修改URL地址 在服务器内部进行转发  浏览器只发起了一次请求  不可以跨站点
//            servletRequest.getRequestDispatcher("/login").forward(servletRequest, servletResponse);
            //使用重定向会修改URL地址 告诉浏览器重新发起一个请求  相当于浏览器一共发起了两次请求  可以跨站点
            ((HttpServletResponse) servletResponse).sendRedirect("/login");
        }
    }

    @Override
    public void destroy() {

    }
}
